package edu.mju.controller;

import edu.mju.util.StrUtil;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 验证码
 * @author wyp
 */
@WebServlet("/captche")
public class CaptcheController extends HttpServlet {
    /**
     * 宽度
     */
    private final int WIDTH=100;
    /**
     * 高度
     */
    private final int HEIGHT=40;
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        BufferedImage img = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
        //获取画笔对象
        Graphics g = img.getGraphics();
        //随机背景颜色
        g.setColor(StrUtil.getRandomColor());
        //指定矩形
        g.fillRect(0,0,WIDTH,HEIGHT);

        //画线
        for(int i=0;i<10;i++) {
            g.setColor(StrUtil.getRandomColor());
            StrUtil.drawLinetoImg(g, WIDTH, HEIGHT);
        }
        //随机验证码颜色
        g.setColor(StrUtil.getRandomColor());
        //字体设置
        g.setFont(new Font("微软雅黑", Font.PLAIN, 30));
        //设置随机字符长度4
        String code = StrUtil.randString(4);

        HttpSession session = req.getSession();
        session.setAttribute("capcode",code);

        g.drawString(code,10,30);
        System.out.println(code);
        g.dispose();//合并以上设置
        //二进制数据流
        ServletOutputStream out=resp.getOutputStream();
        ImageIO.write(img,"jpg",out);
        try {
            out.flush();
        }finally {
            out.close();
        }
    }
}
